package com.waypolice.common.sms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import com.waypolice.common.utils.ReadProperties;

import sun.misc.BASE64Encoder;

/**
 * 数米科技短息发送接口(群发)
 * 备注:群发时,手机号list与内容list索引一一对应,如:手机号1,手机号2--对应的内容--内容1,内容2
 * @author wr
 *
 */
public class SmsGxSend {

	/**
	 * 多个手机号短信发送方法(电话与内容一一对应)
	 * @param mobileList(存放电话)
	 * @param countList(存放内容)
	 * @return 提交成功，返回当前提交数据的唯一标记ID,为null/-999/-99则发送不成功
	 */
	public static String sendByGx(List<String> mobileList,List<String> countList) {
		//内容数组
		int countsize = countList.size();
		String[] count = countList.toArray(new String[countsize]);
		//电话数组
		int mobilesize = mobileList.size();
		String[] mobile = mobileList.toArray(new String[mobilesize]);
		
		Properties properties = ReadProperties.getProperties("caseFailureTime.properties");
		String SMS_UserName = properties.getProperty("SMS_UserName");
		String SMS_PassWord = properties.getProperty("SMS_PassWord");
		
		String result = "-999";
		// 个性群发接口地址
		String url = "http://api.shumi365.com:8090/sms/sendData.do";
		// 客户ID，必填
		String userid = SMS_UserName;
		// 原始密码，必填
		String password = SMS_PassWord;
		// 时间戳，必填
		String timespan = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());// 当前时间转化为yyyymmddhhmmss;
		// MD5加密后密码
		String pwd = getMD5(password + timespan);//原始密码+时间戳做MD5加密，32位大写格式
		// 手机号，必填，多个手机号，个数和内容个数一致
		//String[] mobileArray = {"",""};
		String[] mobileArray = mobile;
		// 内容，必填，多个内容，个数和手机号个数一致
		//String[] contentArray = {"",""};
		String[] contentArray = count;
		// 扩展，选填，可为空，请先询问是否有扩展权限
		String ext = "";
		// 定时时间，选填，可为空
		String attime = "";
		
		// 内容编码方式，可填写：GBK或者UTF-8
		// 如果不填，默认是GBK
		// 服务端对参数content做base64解码时，采用该编码方式解码
		String msgfmt = "GBK";
		StringBuilder sendData = new StringBuilder();
		BASE64Encoder encoder = new BASE64Encoder();
		try {
			// 个性群发，手机号个数和内容个数必须相等
			if (mobileArray != null && contentArray != null && mobileArray.length == contentArray.length) {
				StringBuffer mobileBuff = new StringBuffer("");
				StringBuffer contentBuff = new StringBuffer("");
				// 内容加密
				for (int i=0; i<contentArray.length; i++ ) {
					mobileBuff.append(",").append(mobileArray[i]);
					contentBuff.append(",").append(encoder.encode(contentArray[i].getBytes(msgfmt)));// 做base64加密操作,编码方式使用GBK
				}
				sendData.append("userid=").append(userid)
						.append("&pwd=").append(pwd)
						.append("&timespan=").append(timespan)
						.append("&mobile=").append(mobileBuff.toString().replaceFirst(",", ""))
						.append("&content=").append(contentBuff.toString().replaceFirst(",", ""))
						.append("&ext=").append(ext)
						.append("&msgfmt=").append(msgfmt)
						.append("&attime=").append(attime);
				
				// 发送短信
				result = httpPost(url, sendData.toString(), "utf-8");
			}
		} catch (UnsupportedEncodingException e) {
			result = "-99";
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * http协议提交
	 * @param ulr
	 * @param data
	 * @param charset
	 * @return
	 */
	public static String httpPost(String ulr, String data,String charset) {
		
		URL url=null;
		try {
			url=new URL(ulr);
			HttpURLConnection conn=(HttpURLConnection)url.openConnection();
			conn.setConnectTimeout(30*1000);
			conn.setReadTimeout(30*1000);
			conn.setRequestMethod("POST");
			conn.setDoInput(true);
			conn.setDoOutput(true);
			
			OutputStream out=conn.getOutputStream();
			out.write(data.getBytes(charset));
			out.close();
			
			BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream(),charset));
			StringBuilder response = new StringBuilder();
			String result;
			while (null!=(result=in.readLine())) {
				response.append(result).append("\n");
			}
			in.close();
			return response.toString();
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return "";
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * 用get方式发起请求
	 * @param clientUrl 目标url
	 * @param param 访问数据
	 * @return 成功 返回响应值，失败返回空
	 */
	public static String get(String clientUrl,String param){
		
		URL url=null;
		try {
			url=new URL(clientUrl + "?" + param);
			// 设置通用的请求属性
			HttpURLConnection conn=(HttpURLConnection)url.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setConnectTimeout(30*1000);
			conn.setReadTimeout(30*1000);
			
			BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
			StringBuilder response = new StringBuilder();
			String result;
			while (null!=(result=in.readLine())) {
				response.append(result);
			}
			in.close();
			return response.toString();
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return "";
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * 方法名称：getMD5 
	 * 功    能：字符串MD5加密 
	 * 参    数：待转换字符串 
	 * 返 回 值：加密之后字符串
	 */
	public static String getMD5(String sourceStr){
		String resultStr = "";
		try {
			byte[] temp = sourceStr.getBytes();
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(temp);
			// resultStr = new String(md5.digest());
			byte[] b = md5.digest();
			for (int i = 0; i < b.length; i++) {
				char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
						'9', 'A', 'B', 'C', 'D', 'E', 'F' };
				char[] ob = new char[2];
				ob[0] = digit[(b[i] >>> 4) & 0X0F];
				ob[1] = digit[b[i] & 0X0F];
				resultStr += new String(ob);
			}
			return resultStr;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
	}
}
